const express = require('express')
//导入 Book 模型对象, 用来获取图书数据
const bookModel = require('../models/bookModel')
const { v4: uuidv4 } = require('uuid')

// 创建路由对象
const router = express.Router()

// 书籍列表
router.get('/listAll', async (req, res) => {
  const { pageNo, pageSize, bookName } = req.query
  const page = parseInt(pageNo) || 1
  const size = parseInt(pageSize) || 20
  const skip = (page - 1) * size
  const params = {}
  if (bookName) {
    const name = bookName.slice(1, -1)
    params.bookName = name
  }
  const items = await bookModel.find(params).skip(skip).limit(size)
  const total = await bookModel.find(params)
  res.send({
    code: 200,
    message: '',
    result: {
      items,
      total: total.length,
    },
  })
})

// 新增书籍
router.post('/add', (req, res) => {
  const data = req.body
  if (!data?.bookNo) {
    res.send({
      code: 500,
      message: '书籍编号必填',
    })
    return
  }
  if (!data.bookName) {
    res.send({
      code: 500,
      message: '书籍名称必填',
    })
    return
  }

  bookModel
    .bulkWrite([
      {
        insertOne: {
          document: { ...data, bookId: uuidv4() },
        },
      },
    ])
    .then((resp) => {
      if (!resp) {
        res.send({
          code: 500,
          message: '新增失败',
        })
        return
      }
      res.send({
        code: 200,
        message: '操作成功',
      })
      return
    })
})

// 编辑书籍
router.post('/edit', (req, res) => {
  const { bookId, bookNo, bookName } = req.body

  if (!bookId) {
    res.send({
      code: 500,
      message: '操作失败',
    })
    return
  }
  bookModel.findOneAndUpdate({ bookId }, { bookNo, bookName }).then((resp) => {
    if (!resp) {
      res.send({
        code: 500,
        message: '操作失败',
      })
      return
    }
    res.send({
      code: 200,
      message: '操作成功',
    })
    return
  })
})

// 删除书籍
router.delete('/delBook', (req, res) => {
  const { bookId } = req.query

  if (!bookId) {
    res.send({
      code: 500,
      message: '操作失败',
    })
    return
  }
  bookModel.deleteOne({ bookId }).then((resp) => {
    if (!resp) {
      res.send({
        code: 500,
        message: '操作失败',
      })
      return
    }
    res.send({
      code: 200,
      message: '操作成功',
    })
    return
  })
})

module.exports = router
